package com.lanou3g.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Random;

@Controller
public class UploadController {
    @RequestMapping("/upload")
    public void upload(@RequestParam("head") CommonsMultipartFile img, HttpServletRequest request) throws Exception {
       //CommonsMultipartFile 接受上传文件的类型
        //@RequestParam("head"),有些比较特殊的文件必须使用这个注解,才能正常上传
        System.out.println(img.getSize());//获得上传的文件的大小
        System.out.println(img.getOriginalFilename());//获得上传文件的名字
        String filename = new Date().getTime() + ".jpg";//给上传来的文件用时间取个名
        String realPath = request.getServletContext().getRealPath("/img") + "/" + filename;//获取真实路径
        IOUtils.copy(img.getInputStream(), new FileOutputStream(realPath));//框架里的输入输出流,将上传文件,写到img文件下
    }
}
